<template>
  <div class="wrap">
    <div class="search">
      <div class="query">
        <el-input size="mini" v-model="linkmanName" placeholder="请输入昵称或电话"></el-input>

        <el-button type="primary" size="mini" @click="search" style="margin-left:15px">搜索</el-button>
      </div>
      <div class="right">
        <el-button type="primary" size="mini" @click="passworldState = true">添加联系人</el-button>
        <el-button type="warning" size="mini" @click="expo">导出</el-button>
        <el-button type="warning" size="mini" @click="exppr">导入</el-button>
      </div>
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>

      <el-table-column prop="linkman_name" label="昵称" align="center">
        <template slot-scope="scope">
          <p v-if="!scope.row.editState">{{scope.row.linkman_name}}</p>
          <el-input v-if="scope.row.editState" v-model="scope.row.linkman_name"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="tel" label="电话" align="center">
        <template slot-scope="scope">
          <p v-if="!scope.row.editState">{{scope.row.tel}}</p>
          <el-input v-if="scope.row.editState" v-model="scope.row.tel"></el-input>
        </template>
      </el-table-column>

      <el-table-column prop="name" align="center" label="状态/操作">
        <template slot-scope="scope">
          <div class="caozuo">
            <div>
              <el-button type="primary" size="mini" @click="edit(scope.row)">{{scope.row.text}}</el-button>
              <el-button type="danger" size="mini" @click="del(scope.row)">删除</el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pageSum" v-if="tableData.length">
      <el-pagination
        background
        layout="total,prev, pager, next"
        :page-count="pageCount"
        @current-change="currentMethods"
        :total="total"
         :page-size="pageSize"
      ></el-pagination>
    </div>
    <addUser :passworldState="passworldState" @getUser="getUser"></addUser>
    <el-dialog title="导入联系人" :visible.sync="state" @open="open" @close="close">
      <div class="addImg">
        <div>
          <img src="../assets/drawIMg.png" alt />
          <p>{{text}}</p>
        </div>
        <input type="file" @change="getImg" id="file" class="inpfile" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button type="primary" @click="close(1)">上传</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.addImg {
  width: 100%;
  background: #f0eff2;
  border-radius: 6px;
  height: 200px;
  margin-top: 30px;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  .inpfile {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    opacity: 0;
    width: 100%;
  }
  img {
    width: 100px;
    display: block;
    margin: 0 auto;
  }
  p {
    text-align: center;
    color: #999;
    font-size: 14px;
    margin-top: 15px;
  }
}
.pageSum {
  display: flex;
  margin: 15px;
  justify-content: center;
}
.search {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 30px;
  margin-bottom: 80px;
  .query {
    display: flex;
    align-items: center;
    span {
      color: #999;
      margin-right: 8px;
      display: block;
    }
    .el-input {
      width: auto;
    }
  }
  .right {
    display: flex;
    align-items: center;
  }
}
.caozuo {
  display: flex;
  justify-content: space-around;
  div {
    display: flex;
    justify-content: space-around;
  }
}
</style>
<script>
import addUser from "./addUser";
import { Message } from 'element-ui';

import downloadFile from "js-file-download";
import {
  adduser,
  linkmanList,
  linkmanEdit,
  linkmanDel,
  exist,
  exportLink,
  importTemplate,
  importExcel
} from "../utils/interface";
export default {
  components: {
    addUser
  },
  data() {
    return {
      passworldState: false,
      tableData: [],
      currentPage: 1,
      pageSize: 20,
      total:0,
      linkmanName: "",
      state: false,
      text: "点击上传excel文件",
      xls: "",
      pageCount:0
    };
  },
  methods: {
    // 获取联系人列表
    getList(linkmanName) {
      linkmanList({
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        linkmanName
      }).then(res => {
        res.data.data.list.map(item => {
          item.editState = false;
          item.text = "修改";
        });
        this.pageCount = Math.ceil(res.data.data.total / this.pageSize);
        console.log(this.pageCount)
        this.tableData = res.data.data.list;
        this.total = res.data.data.total
      });
    },
    // 分页
    currentMethods(e) {
      this.currentPage = e;
      this.getList();
    },
    // 添加联系人
    addUsers(e) {
      adduser(e).then(res => {
        if (res.data.code == 200) {
          this.getList();
          this.$message({
            message: "添加成功",
            type: "success"
          });
        }
      });
    },
    // 获取添加的用户信息
    getUser(e) {
      if (e) {
        exist(e).then(res => {
          console.log(res.data.data.queryByName);
          console.log(res.data.data.queryByTel);
          if (res.data.data.queryByName == 0 && res.data.data.queryByTel == 0) {
            this.addUsers(e);
            return false;
          }
          if (res.data.data.queryByName > 0 && res.data.data.queryByTel > 0) {
            this.$alert("用户已存在", "提示", {
              confirmButtonText: "确定"
            });
            return false;
          }
          if (res.data.data.queryByName == 0 && res.data.data.queryByTel > 0) {
            this.$confirm(
              "已存在联系人电话，继续操作会修改对应联系人昵称",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }
            )
              .then(() => {
                this.addUsers(e);
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消添加"
                });
              });
            return false;
          }
          if (res.data.data.queryByName > 0 && res.data.data.queryByTel == 0) {
            this.$confirm(
              "已存在联系人昵称，继续操作会新增一条同昵称不同电话的记录",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }
            )
              .then(() => {
                this.addUsers(e);
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消添加"
                });
              });
            return false;
          }
        });
      }
      this.passworldState = false;
    },
    // 修改
    edit(row) {
      if (row.editState) {
        let data = {
          linkmanId: row.linkman_id,
          linkmanName: row.linkman_name,
          tel: row.tel
        };
        this.$confirm("您将修改该订单, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            linkmanEdit(data).then(res => {
              this.getList();
              this.$message({
                type: "success",
                message: "修改成功!"
              });
              row.editState = false;
              row.text = "修改";
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消修改"
            });
            this.getList();
            row.editState = false;
            row.text = "修改";
          });
      } else {
        row.editState = true;
        row.text = "保存";
      }
    },
    // 删除联系人
    del(row) {
      this.$confirm("您将删除该联系人, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          linkmanDel([row.linkman_id]).then(res => {
            if (res.data.code == 200) {
              this.getList();
              this.$message({
                type: "success",
                message: "删除成功!"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 搜索
    search() {
      this.currentPage = 1;
      this.getList(this.linkmanName);
    },
    open() {
      this.xls = "";
      this.text = "";
      if (document.getElementById("file")) {
        document.getElementById("file").value = "";
      }
    },
    timeD() {
      let date = new Date();
      let y = date.getFullYear(); 
      let m = date.getMonth() + 1; 
      let d = date.getDate(); 
      function rand(n) {
        return n < 10 ? "0" + n : n;
      }
      return y + "-" + rand(m) + "-" + rand(d);
    },
    // 导出
    expo() {
      exportLink().then(res => {
        const data = res.data;
        let r = new FileReader();
        let that = this
        r.onload = function() {
          try {
            let resData = JSON.parse(this.result); // this.result为FileReader获取blob数据转换为json后的数据，即后台返回的原始数据
            if (resData && resData["code"] && resData["code"] !== "200") {
              Message.error(resData.message);
            }
          } catch (err) {
            console.log(that.timeD())
            // return
            const fileName = "通讯录"+that.timeD()+".xls";
            if ("download" in document.createElement("a")) {
              // 非IE下载
              const blob = new Blob([res.data], {
                type: "application/ms-excel"
              });
              const elink = document.createElement("a");
              elink.download = fileName;
              elink.style.display = "none";
              elink.href = URL.createObjectURL(blob);
              document.body.appendChild(elink);
              elink.click();
              URL.revokeObjectURL(elink.href); // 释放URL 对象
              document.body.removeChild(elink);
            }
          }
        };
        r.readAsText(data);
        if (res.data.code == 200) {
        }
      });
    },
    // 导入
    exppr() {
      this.$confirm("导入联系人需要先获取导入的模板?", "提示", {
        confirmButtonText: "我有模板",
        cancelButtonText: "获取模板",
        type: "warning",
        distinguishCancelAndClose: true
      })
        .then(() => {
          this.state = true;
        })
        .catch(action => {
          if (action === "cancel") {
            importTemplate().then(res => {
              const fileName = "通讯录导入模板.xls";
              if ("download" in document.createElement("a")) {
                const elink = document.createElement("a");
                elink.download = fileName;
                elink.style.display = "none";

                elink.href = "http://47.112.155.227" + res.data.data;
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href); // 释放URL 对象
                document.body.removeChild(elink);
              }
            });
          }
        });
    },
    getImg() {
      var reads = new FileReader();
      var param = new FormData();

      var f = document.getElementById("file").files[0];
      console.log(f);
      param.append("file", f);
      this.text = f.name;
      this.$message({
        type: "success",
        message: `已选择${f.name}`
      });
      this.xls = param;
    },
    close(n) {
      if (n) {
        if (!this.xls) {
          this.$alert("请选择上传模板文件", "上传失败", {
            confirmButtonText: "确定"
          });
          this.state = false;
          return false;
        }
        const loading = this.$loading({
          lock: true,
          text: "上传中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        importExcel(this.xls).then(res => {
          loading.close();
          if (res.data.code == 200) {
            this.getList();
            this.$message({
              type: "success",
              message: "导入成功"
            });
          } else {
            this.$alert(
              "导入联系人文件" +
                JSON.stringify(res.data.data.error_position) +
                "行填写错误",
              "上传失败",
              {
                confirmButtonText: "确定"
              }
            );
          }
        });
      }
      this.state = false;
    }
  },
  mounted() {
    this.getList();
  }
};
</script>